<?php
session_start();
if(!(isset($_SESSION['logged']) and $_SESSION['logged'] == 1 )){
    //说明未登录
    //echo "<script>alert('只有登录用户才能投票');location.href='login.html';</script>";
    $info['error'] = 1;
    $info['errMsg'] = '只有登录用户才能投票';
    echo json_encode($info);
    exit;
}
//判断验证码是否正确
if(!isset($_SESSION['authcode']) or ($_SESSION['authcode'] != $_POST['code'])){
    //echo "<script>alert('验证码不正确');history.back();</script>";
    $info['error'] = 1;
    $info['errMsg'] = '验证码不正确';
    echo json_encode($info);
    exit;
}
include_once 'conn.php';
$id = isset($_POST['id'])?$_POST['id']:'0';

if(!$id){
    //echo "<script>alert('参数错误');history.back();</script>";
    $info['error'] = 1;
    $info['errMsg'] = '参数错误';
    echo json_encode($info);
    exit;
}
//先判断投票条件
//1、一个人一天内只能给一个对象投5票。先判断今天投了几票
/*$sql = "SELECT 1 from vote where userID = ".$_SESSION['loggedID']." and objectID = $id and from_unixtime(voteTime, '%Y-%m-%d') = date_format(now(), '%Y-%m-%d')";*/
$sql = "SELECT 1 from vote where userID = ".$_SESSION['loggedID']." and objectID = $id and from_unixtime(voteTime, '%Y-%m-%d') = '" . date("Y-m-d")."'";
$result = mysqli_query($conn,$sql);
//$info = mysqli_fetch_array($result);
/*echo $sql."<br>";
echo mysqli_error($conn);
echo mysqli_num_rows($result);
exit;*/

if(mysqli_num_rows($result) >= 5){
    //不能投票
    //echo "<script>alert('一个人一天内只能给一个对象投5票！');history.back();</script>";
    $info['error'] = 1;
    $info['errMsg'] = '一个人一天内只能给一个对象投5票';
    echo json_encode($info);
    exit;
}
//2、一个用户一天最多只能给3个对象投票
$sql = "SELECT objectID from vote  WHERE userID = ".$_SESSION['loggedID']."  and FROM_UNIXTIME(voteTime,\"%Y-%m-%d\") = DATE_FORMAT(NOW(),\"%Y-%m-%d\")  GROUP BY objectID";
$result = mysqli_query($conn,$sql);
$num = mysqli_num_rows($result);
if($num >= 3){
    //如果投票对象已经达到3个，则要判断当前对象是否在这3个对象的范围内。如果在此之内，则可经继续投票。否则，不能投票。
    $info = mysqli_fetch_all($result,MYSQLI_ASSOC);
    $found = filter_by_value($info,'objectID',$id);
    if(!$found){  //说明未找到，是3个以外的对象，不能投票
        //echo "<script>alert('一个人一天内只能给最多三个对象投票！');history.back();</script>";
        $info['error'] = 1;
        $info['errMsg'] = '一个人一天内只能给最多三个对象投票';
        echo json_encode($info);
        exit;
    }
}

//3、判断当前投票对象是新的对象还是最后一次投过票的对象。如果是新的，就要考虑时间 间隔。旧的则不需要考虑
$sql = "SELECT * FROM `vote`WHERE userID = ".$_SESSION['loggedID']." order by voteTime DESC LIMIT 0,1";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)){
    //说明当前用户投过票，则对比一下当前是不是新的投票对象
    $info = mysqli_fetch_array($result);
    if($info['objectID'] != $id){
        //说明这是一个新的对象，需要判断时间
        if( time() - $info['voteTime'] < 60){
            //说明间隔不足10分钟，不能投票
            //echo "<script>alert('不同投票对象间投票至少要间隔10分钟！');history.back();</script>";
            $info['error'] = 1;
            $info['errMsg'] = '不同投票对象间投票至少要间隔1分钟';
            echo json_encode($info);
            exit;
        }
    }
}

//4、判断当前 IP是否给当前对象投票超过5票
$sql = "SELECT
	COUNT(1) num
FROM
	vote 
WHERE
	userID = ".$_SESSION['loggedID']." 
	AND objectID = $id 
	AND ip = '".get_real_ip()."' 
	AND FROM_UNIXTIME( voteTime, \"%Y-%m-%d\" ) = DATE_FORMAT( NOW( ), \"%Y-%m-%d\" )";
$result = mysqli_query($conn,$sql);
$info = mysqli_fetch_array($result);
if($info['num'] >= 5){
    //echo "<script>alert('同一IP地址只能给一个对象投5票！');history.back(); </script>";
    $info['error'] = 1;
    $info['errMsg'] = '同一IP地址只能给一个对象投5票';
    echo json_encode($info);
    exit;
}
$sql = "update object set vote = vote + 1 where id = $id";
$result = mysqli_query($conn,$sql);

if($result){
    //将本次投票信息记录下来
    $sql = "insert into vote (userID, objectID, voteTime, ip) VALUES ('".$_SESSION['loggedID']."','$id',".time().",'".get_real_ip()."')";
    $result = mysqli_query($conn,$sql);
    if($result){
        //echo "<script>alert('投票成功');location.href='index.php';</script>";
        $info['error'] = 0;
    }
    else{
        //echo "<script>alert('投票失败');history.back();</script>";
        //说明第一次查询成功，第二次查询失败
        $sql = "update object set vote = vote - 1 where id = $id";
        $result = mysqli_query($conn,$sql);
        $info['error'] = 1;
        $info['errMsg'] = '投票失败';
    }
}
else{
    //echo "<script>alert('投票失败');history.back();</script>";
    $info['error'] = 1;
    $info['errMsg'] = '投票失败';
}
echo json_encode($info);
function get_real_ip(){
    $ip = FALSE;
    //客户端IP 或 NONE
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
        if ($ip) {
            array_unshift($ips, $ip);
            $ip = FALSE;
        }
        for ($i = 0; $i < count($ips); $i++) {
            if (!eregi("^(10│172.16│192.168).", $ips[$i])) {
                $ip = $ips[$i];
                break;
            }
        }
    }
    //客户端IP 或 (最后一个)代理服务器 IP
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}
/*根据二维数组某个字段的值查找数组*/
function filter_by_value ($array, $index, $value){
    if(is_array($array) && count($array)>0)
    {
        foreach(array_keys($array) as $key){
            $temp[$key] = $array[$key][$index];

            if ($temp[$key] == $value){
                $newarray[$key] = $array[$key];
            }
        }
    }
    return $newarray;
}